package com.kanjian.music.fragment;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.kanjian.music.R;
import com.kanjian.music.activity.BaseActivity;
import com.kanjian.music.adapter.DownloadedMusicListAdapater;
import com.kanjian.music.database.DatabaseManager;
import com.kanjian.music.database.DownloadListDao;
import com.kanjian.music.database.MusicDao;
import com.kanjian.music.download.MusicDownloadListener;
import com.kanjian.music.download.MusicDownloadTask;
import com.kanjian.music.entity.Music;

/**
 * 
 * @author xuyanjun
 */
public class PlayOnDownloadMusicFragment extends BaseFragment implements
		LoaderCallbacks<Cursor>, MusicDownloadListener {
	private ListView mLv_downloadedMusic;

	private DownloadedMusicListAdapater mListAdapater;

	private ArrayList<Music> mDownloadedMusicList;

	private View mRootView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mListAdapater = new DownloadedMusicListAdapater(
				(BaseActivity) getActivity());
		MusicDownloadTask.registerMusicDownloadListener(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		MusicDownloadTask.unregisterMusicDownloadListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		getLoaderManager().restartLoader(0, null, this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		initView(inflater, container);
		return mRootView;
	}

	private void initView(LayoutInflater inflater, ViewGroup container) {
		if (mRootView == null) {
			mRootView = inflater.inflate(R.layout.fragment_downloaded_music,
					null);
		}
		mLv_downloadedMusic = (ListView) mRootView
				.findViewById(R.id.downloaded_listview);
		mListAdapater.setListView(mLv_downloadedMusic);
		mLv_downloadedMusic.setAdapter(mListAdapater);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		return new DownloadedMusicLoader(getActivity());
	}

	// [MUSIC_ID, DOWNLOAD_TYPE, DOWNLOAD_STATUS, LOCAL_PATH, IS_FAV, USER_PIC,
	// USER_ID, MUSIC_URL, MUSICIAN_LOCATION, PLAY_TIME, USER_NAME, MUSIC_ID,
	// MUSIC_NAME]
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if (cursor != null && cursor.moveToFirst()) {
			int musicIdIndex = cursor
					.getColumnIndex(MusicDao.Properties.MusicId.columnName);
			int downloadTypeIndex = cursor
					.getColumnIndex(DownloadListDao.Properties.DownloadType.columnName);
			int downloadStatusIndex = cursor
					.getColumnIndex(DownloadListDao.Properties.DownloadStatus.columnName);
			int localPathIndex = cursor
					.getColumnIndex(DownloadListDao.Properties.LocalPath.columnName);
			int isFavIndex = cursor
					.getColumnIndex(MusicDao.Properties.IsFav.columnName);
			int userPicIndex = cursor
					.getColumnIndex(MusicDao.Properties.UserPic.columnName);
			int userIdIndex = cursor
					.getColumnIndex(MusicDao.Properties.UserId.columnName);
			int musicUrlIndex = cursor
					.getColumnIndex(MusicDao.Properties.MusicUrl.columnName);
			int musicianLocationIndex = cursor
					.getColumnIndex(MusicDao.Properties.MusicianLocation.columnName);
			int playTimeIndex = cursor
					.getColumnIndex(MusicDao.Properties.PlayTime.columnName);
			int userNameIndex = cursor
					.getColumnIndex(MusicDao.Properties.UserName.columnName);
			int musicNameIndex = cursor
					.getColumnIndex(MusicDao.Properties.MusicName.columnName);

			Music music;
			mDownloadedMusicList = new ArrayList<Music>(cursor.getCount());
			do {
				music = new Music();
				music.setMusicId(cursor.getLong(musicIdIndex));
				music.mDownloadType = cursor.getInt(downloadTypeIndex);
				music.mDownloadStatus = cursor.getInt(downloadStatusIndex);
				music.mLocalPath = cursor.getString(localPathIndex);
				music.setIsFav(cursor.getInt(isFavIndex));
				music.setUserPic(cursor.getString(userPicIndex));
				music.setUserId(cursor.getInt(userIdIndex));
				music.setMusicUrl(cursor.getString(musicUrlIndex));
				music.setMusicianLocation(cursor
						.getString(musicianLocationIndex));
				music.setPlayTime(cursor.getInt(playTimeIndex));
				music.setUserName(cursor.getString(userNameIndex));
				music.setUserId(cursor.getInt(userIdIndex));
				music.setMusicName(cursor.getString(musicNameIndex));
				mDownloadedMusicList.add(music);

			} while (cursor.moveToNext());

			mListAdapater.setMusicList(mDownloadedMusicList);

		}
		cursor.close();
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {

	}

	static class DownloadedMusicLoader extends CursorLoader {

		public DownloadedMusicLoader(Context context) {
			super(context);
		}

		@Override
		public Cursor loadInBackground() {
			String sql = "SELECT * FROM download_list AS d "
					+ "LEFT JOIN music AS m " + "ON d.music_id = m.music_id "
					+ "GROUP BY d.music_id "
					+ "HAVING d.download_status=0 AND d.download_type=1 "
					+ "ORDER BY d.display_order DESC";
			return DatabaseManager.session.getDatabase().rawQuery(sql, null);
		}

	}

	@Override
	public void onStartDownload(Music music) {

	}

	@Override
	public void onProgress(Music music, int progress) {
	}

	@Override
	public void finishDownload(final Music music, int downloadStatus) {
		if (downloadStatus == 0) {
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (mDownloadedMusicList == null) {
						mDownloadedMusicList = new ArrayList<Music>();
					}
					mDownloadedMusicList.add(music);
					mListAdapater.addMusic(music);
				}
			});
		}
	}
}
